import React from 'react'
import { Button, message, Modal} from 'antd'
import Table from '../../../components/Table'
import 'whatwg-fetch'
import API from '../../../axios/api'
import { UserType, } from '../../../utils/system-data'
import { dateToString } from '../../../utils/utils'
import SearchBar from "../../../components/SearchBar";
import {FormModal} from "../../../components/ModalForm";
import SalesDetailList from "./DetailList";
import moment from 'moment';
import {withRouter,Redirect} from "react-router-dom";
import {inject, observer} from "mobx-react";
import { json } from 'graphlib';

require('es6-promise').polyfill();


const columns = [
    { dataIndex: 'AvatarUrl', title: '头像', width: 70,render: (text, record) =>  <img src={text} height="40" width="40" /> },
    { dataIndex: 'RealName', title: '姓名', width: 200,},
    { dataIndex: 'RankTypeString', title: '身份', width: 200,},
    { dataIndex: 'OrderMonthAmount', title: '销售总额', width: 200,},
    { dataIndex: 'GroupBuyingCount', title: '发起活动次数', width: 200,},
    { dataIndex: 'HallName', title: '所属班级', width: 200,},

]
@withRouter @inject('appStore') @observer
class SalesStatistics extends React.Component {
    constructor(props) {
        super(props)
        const {user, rudder, rudderList} = props.appStore
        this.state = {
            user: user,
            rudder: rudder,
            rudderList: rudderList,
            tData: [],
            item: {},
            loading: true,
            modalShowDetail: false,
            modalShowExport: false,
            initHallList: [],
            detailid:'',
            monthTime:'',
            RudderId:'',
            HallId:''
        }
    }

    componentWillReceiveProps(nextProps){
        const {user, rudder, rudderList} = this.props.appStore
         this.setState({
             user: user,
             rudder: rudder,
             rudderList: rudderList,
         })
     }

    // 获取表格数据
    fetchTableData =  () => {
    
        let parms = {
            ...API.config,
            RudderId: this.state.RudderId,
            HallId: this.state.HallId,
            MonthTime: this.state.monthTime,
        }

         API.getRudderMonth(parms).then((res) => {
            if(res.Code === 200) {
                this.setState({
                    tData: res.Data.List
                });
            }
            this.setState({
                loading: false
            });
        })
    }


    // 初始化班级
    initHallList =  async (rudderId) => {
        let _initHallList = []
        let params = {
            ...API.config,
            RudderId: rudderId || this.state.rudder.value
        }
        await API.fetchHallPages(params).then((res) => {
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => _initHallList.push({value: item.Id, mean: item.HallName}))
                this.setState({
                    initHallList: _initHallList
                })
            }
        })
    }
    onCancel = () =>{
        this.setState({
            modalShowDetail: false
        })
    }
    componentWillMount() {
        let data = {}
      if(this.props.location.state && this.props.location.state.monthTime){
        data = {
            monthTime:this.props.location.state.monthTime,
            RudderId:this.props.location.state.RudderId,
            HallId:this.props.location.state.HallId,
        }
        sessionStorage.setItem('porpdata',JSON.stringify(data));
      }else{
         data = JSON.parse(sessionStorage.getItem('porpdata'));
      }


       this.setState(data,()=>{
        this.fetchTableData()
       })
       
    }

    componentDidMount = () => {

        
    }

    tableAction = (actionKey, item) => {
        if (actionKey === 'detail') {
            this.setState({
                modalShowDetail:true,
                item:item
            })
        }
    }

    onSearch = (searchFields) => {
       
    }
    searchRudderChange = (v)=>{
        this.setState({
            searchHallId : "-1"
        })
        this.initHallList(v)
    }
    searchFields = () => {
        let _fields =[{
            title: '班级名称',
            key: 'HallId',
            type: 'select',
            items: () => this.state.initHallList,
        },{
            title: '时间',
            key: 'start',
            type: 'monthPicker',
            defaultValue: moment(new Date(), 'YYYY-MM')
        }]
        if(this.state.user && this.state.user.UserRankType === UserType.ADMIN  || this.state.user.RudderId == "-"){
            _fields = [{
                title: '分舵名称',
                key: 'RudderId',
                type: 'select',
                //defaultValue: this.state.rudder.mean,
                items: () => this.state.rudderList,
                onChange: this.searchRudderChange,
            }, ].concat(_fields)
        }
        return _fields
    }

    showExport = (searchFields) =>{
        const _monthTime = (searchFields && searchFields.start)? dateToString(new Date(searchFields.start)): dateToString(new Date())
        let parms = {
            RudderId:  (searchFields && searchFields.RudderId) || this.state.rudder.value, // 海西分舵 dfhshsdfhdf56735734
            MonthTime: _monthTime,
            DataEmailAddress: '',
        }
        this.setState({
            params: parms,
            modalShowExport: true
        })
    }

    onCancelExport = () => {
        this.setState({
            modalShowExport: false
        })
    }
    exportFields = () => {
        return [{
            label: '邮箱',
            type: 'input',
            name: 'email',
            options: {
                rules: [{
                    required: true,
                    message: '必填!',
                }]
            }
        },]
    }

    goback = () => {
        this.props.history.goBack()
    }

    onExport = (val) =>{
        let parms = this.state.params
        parms.DataEmailAddress = val.email
        API.getRudderMonthDataExcel(parms).then((res) => {
            if(res.Code === 200) {
                message.success('导出成功')
                this.onCancelExport()
            }else{
                message.error(res.Message)
            }
        })
    }

    render() {
        return (
            <div id="wrap">
                 <div style={{ paddingTop: 10 }}>
                    <Button  type="primary" onClick={this.goback}>返回</Button>
                </div>
                <div className="tableBox">
                    <div style={{ paddingTop: 10 }}>
                        <Table
                            onCtrlClick={ this.tableAction }
                            pagination={ true }
                            pageSize={10}
                            header={ columns}
                            data={ this.state.tData }
                            loading={ this.state.loading }
                            action={row => [
                                { key: 'detail', name: '详情', color: 'blue', icon: 'ordered-list'},
                            ]}
                            scroll={{y: 385 }}
                        />
                    </div>
                    <SalesDetailList
                        modalKey="add"
                        visible={this.state.modalShowDetail}
                        title="详情"
                        onOk={this.onOk}
                        onCancel={this.onCancel}
                        userId={this.state.item.UserId}
                        monthTime={this.state.monthTime}
                        width="70%"
                    />
                    <FormModal
                        modalKey="export"
                        visible={this.state.modalShowExport}
                        title="导出"
                        fields={this.exportFields()}
                        onOk={this.onExport}
                        onCancel={this.onCancelExport}
                        okText="保存"
                    />
                </div>
            </div>
        )
    }
}
export default SalesStatistics
